//
//  ARDiscoverPostViewController.swift
//  AquaRaft
//
//  Created by 何启亮 on 2024/4/12.
//

import UIKit

class ARDiscoverPostViewController: ARBaseViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        self.setupUI()
    }

    // MARK: - UI
    
    private func setupUI() {
        self.addChild(editViewController)
        self.view.addSubview(editViewController.view)
        
        editViewController.view.snp.makeConstraints { make in
            make.top.right.left.equalToSuperview()
            // Adaptive height
        }
        
        // nav
        self.ar_configBlackBackItem()
        
        let rightItem = UIBarButtonItem(customView: postBtn)
        self.navigationItem.rightBarButtonItem = rightItem
        
        self.updatePostBtnEnable()
    }
    
    // MARK: - Action
    
    @objc private func postBtnClicked(_ sender: UIButton) {
        guard let work = editViewController.createWork() else {
            return
        }
        self.ar.showLoading()
        ARDataCenter.default.postWork(work) { [weak self] err in
            self?.ar.hideHUD()
            if let err = err {
                self?.ar.makeToast(err.localizedDescription)
                return
            }
            
            // 成功
            self?.ar.makeToast(ARHelper.localString("Publish successful!"))
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2) {
                self?.ar_transitionToBack()
            }
        }
    }
    
    private func updatePostBtnEnable() {
        postBtn.isEnabled = editViewController.judgeWorkCanPost()
    }
    
    // MARK: - Lazy
    
    private lazy var editViewController: ARPostEditController = {
        let vc = ARPostEditController()
        vc.isIndexPostStyle = false
        vc.contentDidChangeCallback = { [weak self] in
            self?.updatePostBtnEnable()
        }
        return vc
    }()
    
    private lazy var postBtn: UIButton = {
        let btn = UIButton.ar.themeStyleButton(height: 28, font: ARHelper.font(12, weight: .regular))
        btn.addTarget(self, action: #selector(postBtnClicked(_:)), for: .touchUpInside)
        btn.setTitle(ARHelper.localString("Post"), for: .normal)
        btn.frame = .init(x: 0, y: 0, width: 50, height: 28)
        return btn
    }()
    
}
